<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="Export2Excel">导出</el-button>
          <el-button v-if="checkPermission('addEmployee')" size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" align="center">
            <template slot-scope="{row}">
              <img
                v-imgerr="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto "
                class="staffPhoto"
                alt=""
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :page-size="pageSetting.size" :total="total" @current-change="currentChange" />
        </el-row>
      </el-card>
      <!-- 放置新增组件 -->
      <Addemployee :show-dialog.sync="showDialog" />
      <!-- 角色设置弹窗 -->
      <AssignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeesEnum from '@/api/constant/employees'
import Addemployee from './components/add-employee'
import AssignRole from './components/assign-role'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters/index'

export default {
  components: {
    Addemployee,
    AssignRole
  },
  data() {
    return {
      pageSetting: {
        page: 1,
        size: 5
      },
      employeeList: [],
      total: 0,
      showDialog: false, // 新增弹出层
      showRoleDialog: false, // 角色设置弹窗
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    //  获取员工的综合列表数据
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.pageSetting)
      this.employeeList = rows
      this.total = total
      console.log(rows)
      console.log(total)
    },
    // 分页发生改变
    currentChange(page) {
      this.pageSetting.page = page
      this.getEmployeeList()
    },
    // 聘用形式格式
    formatEmployment(row, column, cellvalue) {
      const obj = EmployeesEnum.hireType.find(item => item.id === Number(cellvalue))
      return obj ? obj.value : '未知'
    },
    // 删除
    async delEmployee(id) {
      try {
        await this.$confirm('您确定要删除吗?')
        await delEmployee(id)
        this.$message.success('删除成功')
        if (this.employeeList.length <= 1) {
          this.pageSetting.page--
        }
        this.getEmployeeList()
      } catch (err) {
        console.log(err)
      }
    },
    // 导出
    async Export2Excel() {
      const { rows } = await getEmployeeList({
        page: 1,
        size: this.total
      })
      console.log(rows)
      const header = []
      const headers = {
        '工号': 'workNumber',
        '姓名': 'username',
        '手机号': 'mobile',
        '聘用形式': 'formOfEmployment',
        '部门': 'departmentName',
        '入职日期': 'timeOfEntry',
        '转正日期': 'correctionTime'
      }
      for (const key in headers) {
        header.push(key)
      }
      const data = rows.map(item => this.objToArr(item, headers))
      export_json_to_excel({ header, data })
    },
    // 导出数据转换
    objToArr(obj, headers) {
      const arr = []
      for (const key in headers) {
        if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
          arr.push(formatDate(obj[headers[key]]))
        } else if (headers[key] === 'formOfEmployment') {
          const hireType = EmployeesEnum.hireType.find(item => item.id === obj[headers[key]])
          arr.push(hireType ? hireType.value : '未知')
        } else {
          arr.push(obj[headers[key]])
        }
      }
      return arr
    },
    // 编辑角色
    async editRole(id) {
      await this.$refs.assignRole.getUserInfoByid(id)
      this.showRoleDialog = true
      this.userId = id
    }
  }
}
</script>

<style lang="scss" scoped>
.staffPhoto{
      border-radius: 50%;
      width: 100px;
      height: 100px;
      padding: 10px;
      object-fit: cover;
    }
</style>
